package com.heima.comment.service.Imp;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    //远程调用
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private GreenScan greenScan;

    /**
     *加载评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        ResponseResult result = new ResponseResult<>();
        //1. 校验参数
        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //2. 条件查询评论回复信息
        //   条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getSize());
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //   3.1 如果未登录直接 返回评论回复列表
        if (user == null) {
            result = ResponseResult.okResult(apCommentRepays);
        }else {
            //获取回复评论的id集合
            List<String> replayCommentIdList = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
            //获取相关回复评论下的点赞列表
            Query queryApCommentRepayLike = Query.query(Criteria.where("commentRepayId").in(replayCommentIdList).and("authorId").is(user.getId()));
            //当前用户点赞列表的集合
            List<ApCommentRepayLike> repayLikeList = mongoTemplate.find(queryApCommentRepayLike, ApCommentRepayLike.class);
           //对有过点赞的回复评论opention修改为0
            if (CollectionUtils.isNotEmpty(apCommentRepays)) {
                //获取回复评论当前用户点赞列表的id
                List<String> likeCommentRepayId = repayLikeList.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());
                result = ResponseResult.okResult(apCommentRepays.stream().map(apCommentRepay ->parseReplayCommentVo(apCommentRepay,likeCommentRepayId) ));
            }
        }
       return result;
    }
    public ApCommentRepay parseReplayCommentVo(ApCommentRepay apCommentRepay, List<String> likeCommentRepayId){
        ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
        BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
        //遍历用户点赞列表
        if (likeCommentRepayId.contains(apCommentRepay.getId())) {
            apCommentRepayVO.setOperation((short)0);
        }
        return apCommentRepayVO;
    }


    /**
     * 保存评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        //   是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "当前未登录，请先登录!");
        }
        byte[] contentBytes = dto.getContent().getBytes();
        if (contentBytes.length >= 140) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"内容不能超过140个字符");
        }
        //   回复内容安全校验
        //        简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        String needContent = AginstOrNot(dto);
        //2. 根据评论id查询评论信息  检查是否存在
        Query apCommentQuery = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(apCommentQuery, ApComment.class);
        if (apComment != null) {
            //3. 保存评论回复信息
            //远程调用获得用户信息
            ResponseResult<ApUser> responseResult = userFeign.findUserById(user.getId());
            if (!responseResult.checkCode()) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用出错");
            }
            ApUser apUser = responseResult.getData();
            //创建回复评论的内容
            ApCommentRepay apCommentRepay = new ApCommentRepay();
            apCommentRepay.setAuthorId(apUser.getId());
            apCommentRepay.setAuthorName(apUser.getName());
            apCommentRepay.setCommentId(dto.getCommentId());
            if (needContent == null) {
                needContent = dto.getContent();
            }
            apCommentRepay.setContent(needContent);
            apCommentRepay.setLikes(0);
            apCommentRepay.setCreatedTime(new Date());
            apCommentRepay.setUpdatedTime(new Date());
            //创建信息
            mongoTemplate.insert(apCommentRepay);
            //4. 修改评论信息中回复数量 + 1
            Update apCommentUpdate = new Update();

            apCommentUpdate.set("reply",apComment.getReply() + 1)
                    .set("updatedTime",new Date());
            mongoTemplate.updateMulti(apCommentQuery,apCommentUpdate,ApComment.class);

        }else {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"评论已删除");
        }
         return ResponseResult.okResult();
    }
    /**
     * 阿里云检测 获得过滤后的文章内容
     *
     * @param dto
     */
    public String AginstOrNot(CommentRepaySaveDTO dto) {
        String content = dto.getContent();
        if (StringUtils.isEmpty(content)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不能为空!");
        }
        try {
            ScanResult result = greenScan.greenTextScan(content);
            //过滤掉的词汇：替换为**
            content = result.getFilteredContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
    /**
     * 保存评论点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //  回复id不能为空   operation 必须 0 或 1
      if (dto.getOperation() != 0 && dto.getOperation() != 1){
          CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"操作的参数只能是0或1");
      }
        //  校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
      if (user == null){
          CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前状态未登录");
      }
      //判断对应回复是否存在
        Query commentRepayQuery = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay commentRepay = mongoTemplate.findOne(commentRepayQuery, ApCommentRepay.class);
        if (commentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前评论已删除");
        }
        //  校验回复信息是否存在
        //1. 如果是点赞  判断是否点过赞
        Query apCommentLikeQuery = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentRepayId()));
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(apCommentLikeQuery, ApCommentRepayLike.class);
        if (dto.getOperation() == 0 && commentRepayLike == null) {
            //未点过赞， 保存点赞信息
            //并将回复信息的点赞数量字段+1
            commentRepayLike= new ApCommentRepayLike();
            commentRepayLike.setAuthorId(user.getId());
            commentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            commentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.insert(commentRepayLike);
            //   并修改评论信息的点赞数量( + 1)

            Update apCommentReplayUpdate = new Update();
            apCommentReplayUpdate.set("likes",commentRepay.getLikes() + 1)
                    .set("updatedTime",new Date());
            //更新保存的评论集合
            mongoTemplate.updateMulti(commentRepayQuery,apCommentReplayUpdate,ApCommentRepay.class);
        }else  if (commentRepayLike != null && dto.getOperation() == 1){
            //1. 如果是取消赞
            //  删除点赞信息
            mongoTemplate.remove(commentRepayLike);
            // 并将回复信息的点赞数量字段 -1
            //1. 返回当前回复的最新点赞数量      数据的key:  likes
            Update apCommentReplayUpdate = new Update();
            apCommentReplayUpdate.set("likes",commentRepay.getLikes() - 1)
                    .set("updatedTime",new Date());
            //更新保存的评论集合
            mongoTemplate.updateMulti(commentRepayQuery,apCommentReplayUpdate,ApCommentRepay.class);
        }else {
            //点过赞提示请勿重复点赞
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿重复点赞");
        }

        return ResponseResult.okResult();
    }
}
